package com.yowasa.xiuxian.service.helper;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yowasa.xiuxian.entity.bot.channel.CreatDMSReq;
import com.yowasa.xiuxian.entity.bot.channel.DMS;
import com.yowasa.xiuxian.entity.bot.message.Message;
import com.yowasa.xiuxian.entity.bot.message.SendMessageReq;
import com.yowasa.xiuxian.entity.bot.user.User;
import com.yowasa.xiuxian.entity.mys.MysComponent;
import com.yowasa.xiuxian.entity.mys.SendMessage;
import com.yowasa.xiuxian.entity.po.PrivateGuildInfoPO;
import com.yowasa.xiuxian.mapper.PrivateGuildInfoMapper;
import com.yowasa.xiuxian.service.MysReplyServise;
import com.yowasa.xiuxian.service.QQChannelService;
import com.yowasa.xiuxian.util.ContentUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

@Component
public class MessageHelper {
    public static final Logger logger = LoggerFactory.getLogger(MessageHelper.class);
    @Autowired
    private QQChannelService qqChannelService;
    @Autowired
    private MysReplyServise mysReplyServise;
    @Autowired
    private UserHelper userHelper;
    @Autowired
    private PrivateGuildInfoMapper privateGuildInfoMapper;


    private Map<String, PrivateGuildInfoPO> privateGuildMap = Maps.newConcurrentMap();


    /**
     * 回复消息
     * @param message
     * @param content
     */
    public void reply(Message message, String content) {
        SendMessageReq sendMessageReq = new SendMessageReq();
        sendMessageReq.setContent(content);
        sendMessageReq.setMsgId(message.getId());
        logger.info("回复的信息为---{}",content);
        if (message.isDirectMessage()) {
            qqChannelService.sendPrivate(message.getGuildId(), sendMessageReq);
        } else {
            qqChannelService.send(message.getChannelId(),sendMessageReq);
        }
    }

    /**
     * 私信回复消息
     * @param message
     * @param content
     */
    public void replyPrivate(Message message, String content) {
        SendMessageReq sendMessageReq = new SendMessageReq();
        sendMessageReq.setContent(content);
        sendMessageReq.setMsgId(message.getId());
        String guildId=getUserPrivateGuildId(message);
        qqChannelService.sendPrivate(guildId, sendMessageReq);
    }

    private String getUserPrivateGuildId(Message message) {
        String id = message.getAuthor().getId();
        PrivateGuildInfoPO privateGuildInfoPO = privateGuildMap.get(id);
        if (privateGuildInfoPO == null) {
            CreatDMSReq creatDMSReq = CreatDMSReq.builder()
                    .recipientId(id)
                    .sourceGuildId(message.getGuildId())
                    .build();
            DMS dms = qqChannelService.createPrivate(creatDMSReq);
            PrivateGuildInfoPO po = new PrivateGuildInfoPO();
            po.setAccountId(id);
            po.setSourceGuildId(message.getGuildId());
            po.setPrivateGuildId(dms.getGuildId());
            po.setPrivateChannelId(dms.getChannelId());
            privateGuildInfoMapper.insert(po);
            privateGuildMap.put(id, po);
            privateGuildInfoPO = po;
            refreshPrivateGuild();
        }
        return privateGuildInfoPO.getPrivateGuildId();
    }



    /**
     * 获取at的用户
     * @param content
     * @return
     */
    public String getContentAtUserId(String content) {
        List<String> allUser = getAllContentAtUserId(content);
        if (CollectionUtils.isEmpty(allUser)) {
            return null;
        }
        return allUser.get(0);
    }

    public String getMysContentAtUserId(String content) {
        JSONObject jsonObject = JSONUtil.parseObj(content);
        List<String> strings = jsonObject.getJSONObject("mentionedInfo").getJSONArray("userIdList").toList(String.class);
        return strings.get(1);
    }

    public List<String> getAllMysContentAtUserId(String content) {
        JSONObject jsonObject = JSONUtil.parseObj(content);
        return jsonObject.getJSONObject("mentionedInfo").getJSONArray("userIdList").toList(String.class);
    }

    public List<String> getAllContentAtUserId(String content) {
        User botInfo = userHelper.getBotInfo();
        String botId = botInfo.getId();
        List<String> allUser = ContentUtil.getAllUser(content);
        allUser.remove(botId);
        if (CollectionUtils.isEmpty(allUser)) {
            return Lists.newArrayList();
        }
        return allUser;
    }



    private void refreshPrivateGuild() {
        List<PrivateGuildInfoPO> privateGuildInfoPOS = privateGuildInfoMapper.selectList(new LambdaQueryWrapper<>());
        privateGuildInfoPOS.forEach(e->{
            privateGuildMap.put(e.getAccountId(), e);
        });
    }


    // 米游社消息推送
    public void replyMys(SendMessage sendMessage, String format) {
        //sendMessage 收到的消息
        //format  要发送的消息文本
        //todo 在这里可以做参数封装，send方法只做发送
        //降字符串空格分割，然后识别 @ 和 # 封装entities对象，和 MentionedInfo 完成艾特和连接效果
        logger.info("回复的信息为---{}",format);
        logger.info("=======================================");
        // 封装要发送的消息对象
        String s = mysReplyServise.sendTextMessage(sendMessage, format+"\n\n 邀请你加入QQ频道 https://pd.qq.com/s/c65n0az0s  因米游社别野关停，烦请各位玩家加入QQ频道以继续游玩汐颜bot\n频道与米社数据互通，别野关停前随时可迁移存档");
        logger.info("调用发送信息接口结果为---{}",s);

    }

    // 米游社组件消息推送
    public void replyMysPanel(SendMessage sendMessage, String format, List<List<MysComponent>> small,List<List<MysComponent>> mid,List<List<MysComponent>> big) {
        //sendMessage 收到的消息
        //format  要发送的消息文本
        //todo 在这里可以做参数封装，send方法只做发送
        //降字符串空格分割，然后识别 @ 和 # 封装entities对象，和 MentionedInfo 完成艾特和连接效果
        logger.info("回复的信息为---{}",format);
        logger.info("=======================================");
        // 封装要发送的消息对象
        JSONObject componentObj = new JSONObject();

        if(small != null){
            componentObj.put("small_component_group_list", small);
        }
        if(mid != null){
            componentObj.put("mid_component_group_list", mid);
        }
        if(big != null){
            componentObj.put("big_component_group_list", big);
        }
        String s = mysReplyServise.sendPanelTextMessage(sendMessage, format,componentObj);
        logger.info("调用发送信息接口结果为---{}",s);

    }


    // 米游社图片推送
    public void imageSendMys(SendMessage sendMessage, String url) {
        String s = mysReplyServise.sendImageMessage(sendMessage,url);
        logger.info("调用图片信息接口结果为---{}",s);
    }

    // 米游社图片转存
    public String tranferImage(SendMessage sendMessage, String url) {
        String s = mysReplyServise.transferImage(sendMessage,url);
        logger.info("调用图片转存接口结果为---{}",s);
        return s;
    }

    // 米游社获取大别野信息
    public String getVillaInfo(SendMessage sendMessage) {
        String s = mysReplyServise.getVillaInfo(sendMessage);
        logger.info("获取大别野信息结果为---{}",s);
        return s;
    }

    // 米游社获取别野所有身分组信息
    public String getMemberRoles(SendMessage sendMessage) {
        String s = mysReplyServise.getMemberRoles(sendMessage);
        logger.info("获取大别野信息结果为---{}",s);
        return s;
    }

    // 向身份组添加或删除用户
    public void operateMemberToRole(SendMessage sendMessage,JSONObject object) {
        String s = mysReplyServise.operateMemberToRole(sendMessage,object);
        logger.info("向身份组添加或删除用户---{}",s);
    }

    public void removeMember(SendMessage message, long uid) {
        String s = mysReplyServise.removeMember(message,uid);
        logger.info("大别野踢出用户---{}",s);
    }
}
